package com.eric.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class GetRoot {

	public static void main(String[] args) throws IOException {
//		String s = args[0];
		String s = "/home/eric/tmp/urls";
		File file = new File(s);
		GetRoot gr = new GetRoot();
		if (file.exists()) {
			BufferedReader br = new BufferedReader(new FileReader(file));
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file.getAbsolutePath()+".root")));
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(gr.getRoot(line));
				bw.append(gr.getRoot(line));
				bw.append("\n");
			}
			br.close();
			bw.close();
		}else{
			System.out.println(gr.getRoot(s));
		}
	}
	
	public String getRoot (String url) {
    	URL u;
    	StringBuffer root = new StringBuffer();
		try {
			u = new URL(url.toLowerCase());
			String host = u.getHost();
	    	
	    	String[] rootMembers = host.split("\\.");
	    	
	    	//涓�鑸儏鍐典笅锛屽彇host鐨勬渶鍚�2涓紝濡倃ww.abc.com鍙朼bc.com
	    	int n = 2;
	    	
	    	//鍒ゆ柇TLD鍚庣紑鏄惁瓒呰繃1涓紝姣斿edu.cn锛屽鏋滄槸锛屽垯鍒ゆ柇鍩熷悕鍊掓暟绗�2涓悗缂�鏄惁鏄�.com绛夛紙.com.cn褰㈠紡锛�
	    	if (rootMembers.length > 2 ) {
	    		String secondLastMember = rootMembers[rootMembers.length - 2];
	    		
	    		if (secondLastMember.matches("^com$|^net$|^gov$|^edu$|^co$|^org$")) 
	    			n = 3;
	    	}
	    	
	    	//纭畾浜唍鐨勫彇鏁板悗锛屽皢缁撴灉淇濆瓨鍒癝tringBuffer涓紝淇濆瓨椤哄簭鏄嚜宸﹁嚦鍙�
	    	for (int i=n;i>0;i--) {
	    		try {
	    			root.append(rootMembers[host.split("\\.").length-i]);
	        		if ((i-1) > 0) root.append(".");
	    		}catch (java.lang.ArrayIndexOutOfBoundsException e) {
	    		}
	    	}
		} catch (MalformedURLException e1) {
		}
	
    	return root.toString();
    }
}
